<?php

namespace jjl\yii2\db;

class Iterator implements \Iterator {

    private $position = 0;
    private $array;

    public function __construct(array $conf = []) {
        $this->array = $conf;
    }

    public function current() {
        return $this->array[$this->position] ?? null;
    }

    public function key(): \scalar {
        return $this->position;
    }

    public function next() {
        ++$this->position;
    }

    public function rewind() {
        $this->position = 0;
    }

    public function valid(): bool {
        return (bool) $this->current();
    }

    public function __get($name) {
        $result = [];
        do {
            if ($model = $this->current())
                $result[] = $model->{$name};
            else
                break;
            $this->next();
        } while ($this->valid());
        $this->rewind();
        if (($model = $this->current()) && is_object($model->{$name}))
            return new self($result);
        return $result;
    }

}
